<?php

namespace app\api\controller\xiluhouse;

use app\common\controller\Api;
use app\common\model\xiluhouse\MoneyLog;
use app\common\model\xiluhouse\UserProfile;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;
use function GuzzleHttp\Psr7\str;

/**
 * @title   佣金管理
 * @desc    
 */
class Money extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    /**
     * @title 佣金记录列表
     * @param int type 1=普通用户明细,2=房东明细,3=经纪人名称
     *
     */
    public function money_log_list()
    {
        $type = $this->request->param('type');
        $where['user_id'] = $this->auth->id;
        $money_type = [];
        switch ($type){
            case 1:
                $where['type'] = $type;
                //$money_type[] = MoneyLog::MONEY_TYPE_USER_BUY;
                 break;
            case 2:
                $where['type'] = $type;
                $money_type[] = MoneyLog::MONEY_TYPE_LESSOR_RENTER;
                break;
            case 3:
                $where['type'] = $type;
                $money_type[] = MoneyLog::MONEY_TYPE_BROKER_COMMISSION;
                break;
        }
        if($money_type) $where['money_type'] = ['in',$money_type];
        //日期条件
        if($date = $this->request->param('date')){
            $time1 = date('Y-m-01 00:00:00', strtotime($date));
            $time2 = date('Y-m-d 23:59:59', strtotime("$time1 +1 month -1 day"));
            $where['createtime'] = ['between',[strtotime($time1),strtotime($time2)]];
        }

        $model = new \app\common\model\xiluhouse\MoneyLog;
        $list = $model
            ->where($where)
            ->orderRaw('id desc')
            ->paginate()
            ->each(function ($row){
                $extra = json_decode($row->extra,true);
                if(isset($extra['user_avatar'])){
                    $extra['user_avatar'] = cdnurl($extra['user_avatar'],true);
                }
                $row->extra = $extra;
            });
        $this->success('', $list);
    }

    /**
     * @title 提现
     * @desc  提交提现表单
     *
     * @param string $username          无     姓名
     * @param string $mobile            无     手机号
     * @param string $bank_name         无     卡户银行
     * @param string $bank_card_number  无     银行卡号
     * @param float  $money             无     提现金额
     *
     */
    public function withdraw()
    {
        $username = $this->request->param('username/s', '');
        $mobile = $this->request->param('mobile/s', '');
        $bank_name = $this->request->param('bank_name/s', '');
        $bank_card_number = $this->request->param('bank_card_number/s', '');
        $money = $this->request->param('money/f', 0);
        $is_broker = $this->request->param('is_broker');
        if (!$username || !$mobile || !$bank_name || !$bank_card_number || !$money || $money <= 0) {
            $this->error('参数错误');
        }
        if(!in_array($is_broker,[0,1,2])){
            $this->error('不支持的提现类型');
        }
        if($is_broker == 2){
            $field = 'borker_money';
        }else if($is_broker == 1){
            $field = 'lessor_money';
        }else{
            $field = 'money';
        }
        $user_profile = UserProfile::field('user_id,is_broker,money,borker_money,lessor_money')->where('user_id',$this->auth->id)->find();
        // 判断提现金额是否大于用户的金额
        if ($user_profile->$field < $money) {
            $this->error('用户余额不足');
        }
        // 启动事务
        Db::startTrans();
        try {
            $res = \app\common\model\xiluhouse\Withdraw::create([
                'is_broker'         => $is_broker,
                'username'          => $username,
                'mobile'            => $mobile,
                'bank_name'         => $bank_name,
                'bank_card_number'  => $bank_card_number,
                'money' => $money,
                'user_id' => $this->auth->id,
            ]);
            Hook::listen('xiluhouse_withdraw_log',$res);
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('提交成功，请等待审核');
    }

    /**
     * @title 提现记录
     * @desc  该用户的提现记录
     *
     */
    public function withdraw_log_list()
    {
        $is_broker = $this->request->param('is_broker');
        if(!in_array($is_broker,[0,1,2])){
            $this->error('不支持的提现类型');
        }
        $model = new \app\common\model\xiluhouse\Withdraw;
        $list = $model
            ->where('user_id', $this->auth->id)
            ->where('is_broker', $is_broker)
            ->orderRaw('id desc')
            ->paginate();
        $this->success('查询成功', $list);
    }
    /**
     * 房东/经纪人本月收益统计
     */
    public function broker_lessor_statistics(){
        $is_broker = $this->request->param('is_broker');
        $user_id = $this->auth->id;
        $is_broker = $is_broker ? $is_broker : UserProfile::where('user_id',$user_id)->value('is_broker');
        if(!in_array($is_broker,[1,2])){
            $this->error('不支持的类型');
        }
        $small_month = $this->request->param('small_month',1);
        //初始化话月数据
        $year = date('Y');
        $month = (int)date('m');
        $series = [];
        for ($i = $month;$i >= $small_month; $i--){
            $key = $i<10 ? '0'.$i : $i;
            $series[$year.'-'.$key] = [
                'date'      =>  $year.'-'.$key,
                'name'      =>  ($key == $month?'本':$key).'月数据',
                'money'     =>  0,
                'rental_num'=>  0,
                'user_num'  =>  0,
                'view_num'  =>  0
            ];
        }

        $start_time = strtotime($year.'-'.$small_month.'-01');
        $t = date('t',strtotime($year.'-'.$month));
        $end_time = strtotime($year.'-'.$month.'-'.$t.' 23:59:59');

        //新增收入
        $format = '%Y-%m';
        $where = [

            'user_id'      =>  $user_id,
            'createtime'   =>  ['between',[$start_time,$end_time]]
        ];
        $moneyLists = MoneyLog::field("from_unixtime(createtime, '{$format}') AS dates,SUM(money) as total_money")->where($where)->where('type',3)->where('money_type',MoneyLog::MONEY_TYPE_BROKER_COMMISSION)->group('dates')->select();
        foreach($moneyLists as $v){
            $series[$v['dates']]['money'] = $v['total_money'];
        }
        unset($v);
        //新增房源
        $rentalLists = \app\common\model\xiluhouse\Rental::field("from_unixtime(createtime, '{$format}') AS dates,COUNT(id) as total_num")->where($where)->group('dates')->select();
        foreach($rentalLists as $v){
            $series[$v['dates']]['rental_num'] = $v['total_num'];
        }
        unset($v);
        //新增客户
        $userLists = \app\common\model\xiluhouse\AppointLog::field("id,house_state,min_total_price,max_total_price,from_unixtime(distributetime, '{$format}') AS dates,COUNT(id) as total_num")
//            ->with(['user'=>function($query){
//                $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
//            }])
            ->whereBetween("distributetime",[$start_time,$end_time])
            ->where('broker_user_id', $user_id)
            ->where('state','>=', 1)
            //->where('is_using', 2)
            //->where('appoint_log.is_using', 2)
            //->where('appoint_log.rental_id', 0)
            ->where('user_id', 'neq', $user_id)
            ->select();
        foreach($userLists as $v){
            if(!$v['id']) continue;
            $series[$v['dates']]['user_num'] = $v['total_num'];
        }
        unset($v);
        //新增带看
        $userLists = \app\common\model\xiluhouse\AppointLog::field("id,house_state,min_total_price,max_total_price,DATE_FORMAT('view_date','{$format}') AS dates,COUNT(id) as total_num")
//            ->with(['user'=>function($query){
//                $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
//            }])
            ->whereBetween("view_date",[$start_time,$end_time])
            ->where('broker_user_id', $user_id)
            ->where('state','>=', 1)
            ->where('house_state','=', 2)
            //->where('is_using', 2)
            //->where('appoint_log.is_using', 2)
            //->where('appoint_log.rental_id', 0)
            ->where('user_id', 'neq', $user_id)
            ->select();
        foreach($userLists as $v){
            if(!$v['id']) continue;
            $series[$v['dates']]['view_num'] = $v['total_num'];
        }
        unset($v);

        $this->success('',array_values($series));
    }

}
